<template>
	<view class="container">
		<view class="welcome-section">
			<text class="welcome-text">欢迎回来，{{username}}！</text>
			<text class="sub-text">今日接龙 {{todayMinutes}} 个</text>
		</view>

		<view class="stats-card">
			<view class="card-header">
				<text class="card-title">接龙统计</text>
				<picker mode="date" fields="month" @change="changeMonth">
					<view class="date-picker">
						<text>{{currentMonth}}</text>
						<image class="calendar-icon" src="/static/icons/calendar.png"></image>
					</view>
				</picker>
			</view>

			<!-- 图表容器 -->
			<view class="chart-wrapper">
				<canvas canvas-id="timeChart" id="timeChart" class="chart"></canvas>
			</view>

			<!-- 图表图例 -->
			<view class="chart-legend">
				<view class="legend-item">
					<view class="legend-color" style="background-color: #5B8FF9;"></view>
					<text class="legend-text">每日接龙</text>
				</view>
			</view>
		</view>

		<!-- 开始游戏按钮 -->
		<view class="start-game-btn" @click="startGame">
			<image class="btn-icon" src="/static/icons/play.png"></image>
			<text class="btn-text">开始成语接龙</text>
		</view>
	</view>
</template>

<script>
	import uCharts from '@/node_modules/@qiun/ucharts/u-charts.min.js'
	import auth from '../../common/auth.js'
	let timeChart = null

	export default {
		data() {
			return {
				username: '接龙达人',
				todayMinutes: 0,
				currentMonth: this.formatDate(new Date()),
				cWidth: 0,
				cHeight: 0,
				chartData: {
					categories: [],
					series: [{
						name: '接龙时间',
						data: [],
						color: '#5B8FF9'
					}]
				}
			}
		},
		onShow() {
			// 获取用户信息
			const nickname = uni.getStorageSync('nickname')
			if (nickname) {
				this.username = nickname;
			}

			// 初始化图表尺寸
			this.cWidth = uni.upx2px(630)
			this.cHeight = uni.upx2px(400)

			// 加载数据
			this.loadGameTimeData()
		},
		methods: {
			formatDate(date) {
				const year = date.getFullYear()
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				return `${year}-${month}`
			},

			changeMonth(e) {
				this.currentMonth = this.formatDate(new Date(e.detail.value))
				this.loadGameTimeData()
			},

			async loadGameTimeData() {
				uni.showLoading({
					title: '加载中...'
				})

				try {
					const res = await uni.request({
					  url: 'http://localhost:8003/api/v1/game/chart',
					  method: 'GET',
					  data: { month: this.currentMonth },
					  header: { 'Authorization': 'Bearer ' + uni.getStorageSync('token') }
					})
					
					if (res.statusCode === 200 && res.data.code === 200) {
						let result = res.data.data;		
						// 生成更美观的模拟数据
						//const mockData = this.generateBeautifulData()
						this.chartData.categories = result.chart.categories
						this.chartData.series[0].data = result.chart.data
						this.todayMinutes = result.today
						this.$nextTick(() => {
							this.drawChart()
						})
					} else {
						throw new Error(res.data.message || '加载游戏数据失败')
					}

					
				} catch (error) {
					console.error('加载数据失败:', error)
				} finally {
					uni.hideLoading()
				}
			},

			async drawChart() {
				try {
					const canvasNode = await new Promise((resolve, reject) => {
						const query = uni.createSelectorQuery().in(this)
						query.select('#timeChart')
							.fields({
								node: true,
								size: true
							})
							.exec(res => {
								res[0] ? resolve(res[0].node) : reject('未获取到canvas节点')
							})
					})

					canvasNode.width = this.cWidth
					canvasNode.height = this.cHeight

					timeChart = new uCharts({
						$this: this,
						canvas: canvasNode,
						context: canvasNode.getContext('2d'),
						type: 'column',
						categories: this.chartData.categories,
						series: this.chartData.series,
						width: this.cWidth,
						height: this.cHeight,
						padding: [15, 1, 40, 1],
						extra: {
							column: {
								type: 'group',
								width: this.cWidth * 1 / this.chartData.categories.length,
								activeBgColor: '#00000010',
								linearType: 'custom'
							},
							tooltip: {
								showBox: true,
								padding: 6,
								borderColor: '#5B8FF9',
								borderWidth: 1,
								backgroundColor: 'rgba(255, 255, 255, 0.9)',
								textColor: '#333',
								legendColor: '#5B8FF9'
							},
							legend: {
								show: false // 使用自定义图例
							},
							xAxis: {
								disableGrid: true,
								axisLineColor: '#eee',
								fontColor: '#666',
								boundaryGap: 'justify',
								rotateLabel: false,
								// 确保所有日期显示
								scrollShow: true,
								itemCount: 7,
								// 避免标签被截断
								labelBreak: true,
								labelOffset: 5
							},
							yAxis: {
								gridType: 'dash',
								dashLength: 4,
								gridColor: '#f0f0f0',
								data: [{
									min: 0
								}],
								fontColor: '#666',
								splitNumber: 5,
								format: val => `${val}分钟`
							},
							animation: {
								duration: 800,
								easing: 'elasticOut'
							}
						}
					})
				} catch (error) {
					console.error('绘制图表失败:', error)
				}
			},

			startGame() {
				//验证是否登录
				if (!auth.checkLogin()) {
				  auth.authInterceptor()
				}else{
					uni.navigateTo({
						url: '/pages/game/game'
					})
				}
				
			}
		},

		onUnload() {
			if (timeChart) {
				timeChart.dispose()
				timeChart = null
			}
		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;
		overflow: hidden;
		background-color: #f8fafc;
	}

	.container {
		height: 100vh;
		width: 100vw;
		overflow: hidden;
		padding: 30rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
	}

	.welcome-section {
		margin-bottom: 40rpx;

		.welcome-text {
			font-size: 40rpx;
			font-weight: bold;
			color: #333;
			display: block;
			margin-bottom: 10rpx;
		}

		.sub-text {
			font-size: 28rpx;
			color: #666;
		}
	}

	.stats-card {
		background-color: #fff;
		border-radius: 24rpx;
		padding: 30rpx;
		box-shadow: 0 10rpx 30rpx rgba(91, 143, 249, 0.1);
		margin-bottom: 40rpx;
		flex: 0.5;

		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;

			.card-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}

			.date-picker {
				display: flex;
				align-items: center;
				padding: 12rpx 24rpx;
				background-color: rgba(91, 143, 249, 0.1);
				border-radius: 40rpx;
				font-size: 26rpx;
				color: #5B8FF9;

				.calendar-icon {
					width: 30rpx;
					height: 30rpx;
					margin-left: 10rpx;
				}
			}
		}

		.chart-wrapper {
			width: 100%;
			height: 350rpx;
			margin-bottom: 20rpx;

			.chart {
				width: 100%;
				height: 100%;
			}
		}

		.chart-legend {
			display: flex;
			justify-content: center;

			.legend-item {
				display: flex;
				align-items: center;

				.legend-color {
					width: 24rpx;
					height: 24rpx;
					border-radius: 6rpx;
					margin-right: 10rpx;
				}

				.legend-text {
					font-size: 26rpx;
					color: #666;
				}
			}
		}
	}

	.start-game-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		background: linear-gradient(135deg, #5B8FF9, #36D1DC);
		border-radius: 60rpx;
		height: 100rpx;
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
		box-shadow: 0 10rpx 30rpx rgba(91, 143, 249, 0.3);
		margin-bottom: env(safe-area-inset-bottom);
		transition: all 0.3s;

		&:active {
			transform: scale(0.98);
			opacity: 0.9;
		}

		.btn-icon {
			width: 40rpx;
			height: 40rpx;
			margin-right: 15rpx;
		}
	}
</style>